﻿namespace FSharpChess
module Attack =
    let PlayerBlack = Player.black()
    let PlayerWhite = Player.white()
    let getPlayer col = if col then PlayerWhite else PlayerBlack 
    let OtherPlayer pr = if pr.prIsWhite then PlayerBlack else PlayerWhite
    let CanBeMovedToBy(ord,pr,psn,testK) =
        //move based results
        let rec CanBmovs nm ml =
            match ml with
                |[] -> false
                | ml ->  
                    let cord = ml.Head 
                    if psn.Sqs.[cord] = -1 then
                        CanBmovs nm ml.Tail 
                    elif psn.Pcs.[psn.Sqs.[cord]].pcIsWhite = pr.prIsWhite && psn.Pcs.[psn.Sqs.[cord]].Name=nm then
                        true
                    else
                        CanBmovs nm ml.Tail
        // Pawn
        let canbMv2P() = CanBmovs enmName.Pawn (if pr.prIsWhite then Ref.attsPWto.[ord] else Ref.attsPBto.[ord])
        // Knight
        let canbMv2N() = CanBmovs enmName.Knight Ref.movsN.[ord]
        //get rays based results
        let rec CanBrays nm r rl =
            match r with
                |[] -> if rl=[] then false else CanBrays nm rl.Head rl.Tail
                | r ->  
                    let cord = r.Head 
                    if psn.Sqs.[cord] = -1 then
                        CanBrays nm r.Tail rl 
                    elif psn.Pcs.[psn.Sqs.[cord]].pcIsWhite = pr.prIsWhite && (psn.Pcs.[psn.Sqs.[cord]].Name=nm || psn.Pcs.[psn.Sqs.[cord]].Name=enmName.Queen ) then
                        true
                    else
                        if rl=[] then false else CanBrays nm rl.Head rl.Tail
        // Bishop & Queen
        let canbMv2B() = CanBrays enmName.Bishop Ref.raysB.[ord].Head Ref.raysB.[ord].Tail
        // Rook & Queen
        let canbMv2R() = CanBrays enmName.Rook Ref.raysR.[ord].Head Ref.raysR.[ord].Tail
        // King!
        let canbMv2K() = CanBmovs enmName.King Ref.movsK.[ord]
        canbMv2P()||canbMv2N()||canbMv2B()||canbMv2R()||(testK && canbMv2K())
    let is_in_check(pr,psn,testK) =
        let kingsq = if pr.prIsWhite then 4 else 20
        CanBeMovedToBy(psn.Pcs.[kingsq].SquareOrd,OtherPlayer(pr),psn,testK)
    let rec line_is_empty psn sqfrom sqto inc =
        if sqfrom+inc=sqto then
            true
        elif psn.Sqs.[sqfrom+inc] <> -1 then
            false
        else
            line_is_empty psn (sqfrom+inc) sqto inc
             

